package com.ruoyi.project.goods.goods.controller;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.goods.goods.domain.Goods;
import com.ruoyi.project.goods.goods.service.IGoodsService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品Controller
 * 
 * @author lonsn
 * @date 2020-11-04
 */
@Controller
@RequestMapping("/goods/goods")
public class GoodsController extends BaseController
{
    private String prefix = "goods/goods";

    @Autowired
    private IGoodsService goodsService;

    @RequiresPermissions("goods:goods:view")
    @GetMapping()
    public String goods()
    {
        return prefix + "/goods";
    }

    /**
     * 查询商品列表
     */
    @RequiresPermissions("goods:goods:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Goods goods)
    {
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @RequiresPermissions("goods:goods:export")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Goods goods)
    {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        return util.exportExcel(list, "goods");
    }

    /**
     * 新增商品
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增商品
     */
    @GetMapping("/addByWx")
    public String addByWx()
    {
        return prefix + "/addByWx";
    }

    /**
     * 新增保存商品
     */
    @RequiresPermissions("goods:goods:add")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(value="file",required=false) MultipartFile file, Goods goods) throws java.io.IOException
    {
        if(file!=null){
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            if(!StringUtils.converNull(fileName).equals("")){
                goods.setImgPath(fileName);
            }
        }
        AjaxResult r=new AjaxResult(AjaxResult.Type.SUCCESS,"保存成功");
        goodsService.insertGoods(goods);
        try {
            goodsService.insertGoods(goods);
        }catch (Exception e){
            r=new AjaxResult(AjaxResult.Type.ERROR,"保存失败，检查款号是否重复"+e.getMessage());
        }
        return  r;
    }

    /**
     * 修改商品
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        Goods goods = goodsService.selectGoodsById(id);
        mmap.put("goods", goods);
        return prefix + "/edit";
    }

    /**
     * 修改保存商品
     */
    @RequiresPermissions("goods:goods:edit")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(value="file",required=false) MultipartFile file,Goods goods) throws java.io.IOException
    {
        if(file!=null){
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            if(!StringUtils.converNull(fileName).equals("")){
                goods.setImgPath(fileName);
            }
        }

        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除商品
     */
    @RequiresPermissions("goods:goods:remove")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(goodsService.deleteGoodsByIds(ids));
    }



    /**
     * 根据条码获取商品内容
     */
    @PostMapping("/selectGoodsByKey")
    @ResponseBody
    public AjaxResult selectGoodsByKey(Goods goods)    {
        goods=goodsService.selectGoodsByKey(goods);
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", 200);
        ajax.put("value", goods);
        return ajax;
    }


    /**
     * 新增商品
     */
    @GetMapping("/check_goods")
    public String checkGoods()
    {
        return prefix + "/check_goods";
    }

    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        /*if (StringUtils.isNull(userList) || userList.size() == 0)        {
            throw new BusinessException("导入用户数据不能为空！");
        }*/
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        List<Goods> list = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        //String message = userService.importUser(list, updateSupport, operName);
        return  goodsService.insertBatchGoods(list,operName);
    }
}
